from binance.client import Client
from collections import defaultdict
import json
import time
from datetime import datetime

client = Client()

client.d
all_symbol = ['BTCUSDT','ETHUSDT']


# 获取订单簿数据
def get_order_book():
    for symbol in all_symbol:
        while(1):
            try:
                depth = client.futures_order_book(symbol=symbol, limit=1000)  # 获取最多1000条数据
                # 将订单簿数据写入TXT文件，a追加模式
                current_time = datetime.now().strftime('%m_%d_%H')
                with open('./order_book/'+current_time+'_'+symbol+'.txt', 'a') as file:
                    file.write(json.dumps(depth) + '\n')
                time.sleep(1)
                break
            except Exception as e:
                print("获取数据失败 重新获取")


# # 初始化分类结果
# buy_levels = defaultdict(float)  # 买单分类汇总
# sell_levels = defaultdict(float)  # 卖单分类汇总

# # 定义一个函数来根据价格分类
# def categorize_price(price):
#     return int(float(price) // 100 * 100)

# # 处理买单数据
# for price, quantity in depth['bids']:
#     level = categorize_price(price)
#     buy_levels[level] += float(quantity)

# # 处理卖单数据
# for price, quantity in depth['asks']:
#     level = categorize_price(price)
#     sell_levels[level] += float(quantity)

# print("\n卖单分类 (每100美元):")
# for level in sorted(sell_levels.keys()):
#     print(f"价格区间: {level} - {level+99}, 数量: {sell_levels[level]:.4f} BTC")

# # 按区间输出分类后的结果
# print("\n买单分类 (每100美元):")
# for level in sorted(buy_levels.keys(), reverse=True):
#     print(f"价格区间: {level} - {level+99}, 数量: {buy_levels[level]:.4f} BTC")

